//
//  BMKLocationModel.m
//  BaZhou
//
//  Created by JL on 15/10/7.
//  Copyright (c) 2015年 ZJ. All rights reserved.
//

#import "AMKLocationModel.h"

@implementation AMKLocationModel

{
    NSMutableArray * _finishArray;
    NSMutableArray * _geoCodeAddressFinishArray;
    NSMutableArray * _filedArray;
    NSMutableArray * _poiSearchResultArray;
    
    //void(^finish)(CLLocationCoordinate2D,NSString *cityName);
    //void(^geoCodeAddressFinish)(CLLocationCoordinate2D,BMKReverseGeoCodeResult *);
    //void(^field)(BMKSearchErrorCode error);
    //void(^poiSearchResult)(NSArray *);
}
+ (instancetype)sharedBMKLocationModel
{
    static AMKLocationModel *_sharedLocationModel=nil;
    static dispatch_once_t once_t;
    dispatch_once(&once_t, ^{
        _sharedLocationModel=[[AMKLocationModel alloc] init];
    });
    return _sharedLocationModel;
    
}
-(instancetype)init
{
    if ([super init]) {
        _finishArray = [[NSMutableArray alloc] init];
        _geoCodeAddressFinishArray = [[NSMutableArray alloc] init];
        _filedArray = [[NSMutableArray alloc] init];
        _poiSearchResultArray = [[NSMutableArray alloc] init];
        
        self.locService=[[AMapLocationManager alloc] init];
//        self.geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
//        self.search=[[BMKPoiSearch alloc] init];
        
    }
    return self;
}
- (void)stopLocation
{
    self.locService.delegate = nil;
//    self.geoCodeSearch.delegate=nil;
//    self.search.delegate=nil;
    [self.locService stopUpdatingLocation];
    
}
- (void)startLocation
{
    self.locService.delegate=self;
//    self.geoCodeSearch.delegate=self;
//    self.search.delegate=self;
    [self.locService startUpdatingLocation];
}
- (void)removeAllBlock
{
    [_finishArray removeAllObjects];
    [_geoCodeAddressFinishArray removeAllObjects];
    [_filedArray removeAllObjects];
    [_poiSearchResultArray removeAllObjects];
}
#pragma locationDelegate

//处理位置坐标更新
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",location.coordinate.latitude,location.coordinate.longitude);
    //停止定位
    [self.locService stopUpdatingLocation];
    if (!self.canGeoCode) {
        //如果不需要检索完成定位搜索
        for (LocationFinish finish in _finishArray) {
            if (finish) {
                finish(location.coordinate,self.locationCity);
                self.canGeoCode = NO;
            }
        }
        [_finishArray removeAllObjects];
        
        for (GeoCodeAddressFinish geoCodeAddressFinish in _geoCodeAddressFinishArray) {
            if (geoCodeAddressFinish) {
                geoCodeAddressFinish(location.coordinate,nil);
            }
        }
        [_geoCodeAddressFinishArray removeAllObjects];
        [self stopLocation];
        return;
    }
    
}
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error
{
//    if (![BMKLocationModel isOpenLocation]) {
//        CLLocationCoordinate2D coor2D;
//        coor2D.latitude=39.06;
//        coor2D.longitude=116.24;
//        for (LocationFinish finish in _finishArray) {
//            if (finish) {
//                LocationFinish finish = [_finishArray firstObject];
//                finish(coor2D,@"北京市");
//            }
//        }
//        [_finishArray removeAllObjects];
//        for (GeoCodeAddressFinish geoCodeAddressFinish in _geoCodeAddressFinishArray) {
//            if (geoCodeAddressFinish) {
//                geoCodeAddressFinish(coor2D,nil);
//            }
//        }
//        [_geoCodeAddressFinishArray removeAllObjects];
//    }
    for (LocationField field in _filedArray) {
        if (field) {
            field();
        }
    }
    [self removeAllBlock];
}
#pragma mark反地理编码
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if (response.regeocode !=nil ) {
//        if([result.addressDetail.city hasSuffix:@"市"]){
//            self.locationCity = [result.addressDetail.city substringToIndex:result.addressDetail.city.length-1];
//        }else if([result.addressDetail.city hasSuffix:@"县"]){
//            self.locationCity = [result.addressDetail.city substringToIndex:result.addressDetail.city.length-1];
//        }else{
//            self.locationCity=result.addressDetail.city;
//        }
        self.locationCity=response.regeocode.addressComponent.city;
        //需要检索
        for (LocationFinish finish in _finishArray) {
            CLLocationCoordinate2D location = {response.regeocode.addressComponent.streetNumber.location.latitude,response.regeocode.addressComponent.streetNumber.location.longitude};
            if (finish) {
                finish(location,self.locationCity);
            }
        }
        [_finishArray removeAllObjects];
        for (GeoCodeAddressFinish geoCodeAddressFinish in _geoCodeAddressFinishArray) {
            CLLocationCoordinate2D location = {response.regeocode.addressComponent.streetNumber.location.latitude,response.regeocode.addressComponent.streetNumber.location.longitude};
            if (geoCodeAddressFinish) {
                geoCodeAddressFinish(location,response);
            }
        }
        [_geoCodeAddressFinishArray removeAllObjects];
    }else{
        NSLog(@"检索失败");
        for (LocationField field in _filedArray) {
            if (field) {
                field();
            }
        }
        [_filedArray removeAllObjects];
    }
    self.canGeoCode=NO;
}
////模糊搜索
//- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPoiResult*)poiResultList errorCode:(BMKSearchErrorCode)error
//{
//    if (error==BMK_SEARCH_NO_ERROR) {
//        for (PoiSearchResult poiSearchResult in _poiSearchResultArray) {
//            if (poiSearchResult) {
//                poiSearchResult(poiResultList.poiInfoList);
//            }
//        }
//        [_poiSearchResultArray removeAllObjects];
//    }else {
//        for (PoiSearchResult poiSearchResult in _poiSearchResultArray) {
//            if (poiSearchResult) {
//               poiSearchResult(nil);
//            }
//        }
//        [_poiSearchResultArray removeAllObjects];
//    }
//}

- (void)loctionCanGeoCode:(BOOL)canGeoCode Finish:(LocationFinish)locationFinish locationField:(LocationField)locationField
{
    //定位服务开启
    self.canGeoCode=canGeoCode;
    [self startLocation];
    [_finishArray addObject:[locationFinish copy]];
    [_filedArray addObject:[locationField copy]];
}
+ (instancetype)BMKLocationModelLoctionCanGeoCode:(BOOL)canGeoCode Finish:(LocationFinish)locationFinish locationField:(LocationField)locationField
{
    AMKLocationModel *model=[AMKLocationModel sharedBMKLocationModel];
    [model loctionCanGeoCode:canGeoCode Finish:^(CLLocationCoordinate2D coor2D, NSString *cityName) {
        locationFinish(coor2D,cityName);
    } locationField:^() {
        locationField();
    }];
    return model;
}
//- (void)loctionAddResult:(BOOL)canGeoCode Finish:(GeoCodeAddressFinish)locationFinish locationField:(LocationField)locationField
//{
//    if (![BMKLocationModel isOpenLocation]) {
//        
//    }else{
//        //定位服务开启
//        self.canGeoCode=canGeoCode;
//        [self startLocation];
//        [_geoCodeAddressFinishArray addObject:[locationFinish copy]];
//        [_filedArray addObject:[locationField copy]];
//    }
//}
//
//+ (instancetype)BMKLocationModelLoctionAddResult:(BOOL)canGeoCode Finish:(GeoCodeAddressFinish)locationFinish locationField:(LocationField)locationField
//{
//    BMKLocationModel *model=[BMKLocationModel sharedBMKLocationModel];
//    [model loctionAddResult:canGeoCode Finish:^(CLLocationCoordinate2D coor2D, BMKReverseGeoCodeResult *addResult) {
//        locationFinish(coor2D,addResult);
//    } locationField:^(BMKSearchErrorCode error) {
//        locationField(error);
//    }];
//    return model;
//}
//
//- (void)poiSearchKeyWord:(NSString *)keyWord finish:(PoiSearchResult)poiSearch
//{
//    @synchronized(self) {
//        [self loctionCanGeoCode:YES Finish:^(CLLocationCoordinate2D coor2D, NSString *cityName) {
//            if ([BMKLocationModel isOpenLocation]) {
//                BMKNearbySearchOption *searchOption=[[BMKNearbySearchOption alloc] init];
//                searchOption.location= coor2D;
//                searchOption.keyword=keyWord;
//                searchOption.pageIndex=0;
//                searchOption.pageCapacity=50;
//                searchOption.radius=1000000000;
//                searchOption.sortType=BMK_POI_SORT_BY_COMPOSITE;
//                BOOL isRet=[self.search poiSearchNearBy:searchOption];
//                if (isRet) {
//                    [_poiSearchResultArray addObject:[poiSearch copy]];
//                }else{
//                    NSLog(@"检索失败");
//                    poiSearch(nil);
//                }
//            }else{
//                UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请开启定位功能!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
//                [alertView show];
//                poiSearch(nil);
//            }
//        } locationField:^(BMKSearchErrorCode error) {
//            poiSearch(nil);
//        }];
//    }
//}
//+ (instancetype)BMKLocationModelpoiSearchKeyWord:(NSString *)keyWord finish:(PoiSearchResult)poiSearch
//{
//    BMKLocationModel *model=[BMKLocationModel sharedBMKLocationModel];
//    [model poiSearchKeyWord:keyWord finish:^(NSArray *poiInfoArray) {
//        poiSearch(poiInfoArray);
//    }];
//    return model;
//}
//- (void)poiSearchKeyWord:(NSString *)keyWord city:(NSString *)cityName finish:(PoiSearchResult)poiSearch
//{
//    @synchronized(self) {
//        [self loctionCanGeoCode:YES Finish:^(CLLocationCoordinate2D coor2D, NSString *cityName) {
//            if ([BMKLocationModel isOpenLocation]) {
//                BMKCitySearchOption *searchOption=[[BMKCitySearchOption alloc] init];
//                searchOption.city = cityName;
//                searchOption.keyword=keyWord;
//                searchOption.pageIndex=0;
//                searchOption.pageCapacity=50;
//                BOOL isRet=[self.search poiSearchInCity:searchOption];
//                if (isRet) {
//                    [_poiSearchResultArray addObject:[poiSearch copy]];
//                }else{
//                    NSLog(@"检索失败");
//                    poiSearch(nil);
//                }
//            }else{
//                UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请开启定位功能!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
//                [alertView show];
//                poiSearch(nil);
//            }
//        } locationField:^(BMKSearchErrorCode error) {
//            poiSearch(nil);
//        }];
//    }
//}
//+ (instancetype)BMKLocationModelpoiSearchKeyWord:(NSString *)keyWord city:(NSString *)city finish:(PoiSearchResult)poiSearch
//{
//    BMKLocationModel *model=[BMKLocationModel sharedBMKLocationModel];
//    [model poiSearchKeyWord:keyWord city:city finish:^(NSArray *poiInfoArray) {
//        poiSearch(poiInfoArray);
//    }];
//    return model;
//}
//- (void)poiNearbySearchKeyWord:(NSString *)keyWord finish:(PoiSearchResult)poiSearch
//{
//    [self loctionAddResult:YES Finish:^(CLLocationCoordinate2D coor2D, BMKReverseGeoCodeResult *addResult) {
//        if ([BMKLocationModel isOpenLocation]) {
//            BMKNearbySearchOption *searchOption=[[BMKNearbySearchOption alloc] init];
//            searchOption.keyword = addResult.address;
//            searchOption.location = coor2D;
//            searchOption.pageIndex = 0;
//            searchOption.pageCapacity = 50;
//            searchOption.radius = 1000000000;
//            searchOption.sortType=BMK_POI_SORT_BY_COMPOSITE;
//            BOOL isRet=[self.search poiSearchNearBy:searchOption];
//            if (isRet) {
//                [_poiSearchResultArray addObject:[poiSearch copy]];
//            }else{
//                NSLog(@"检索失败");
//                poiSearch(nil);
//            }
//        }else{
//            UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请开启定位功能!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
//            [alertView show];
//            poiSearch(nil);
//        }
//    } locationField:^(BMKSearchErrorCode error) {
//        poiSearch(nil);
//    }];
//}
//
//+ (instancetype)BMKNearbyLocationModelpoiSearchKeyWord:(NSString *)keyWord finish:(PoiSearchResult)poiSearch
//{
//    BMKLocationModel *model=[BMKLocationModel sharedBMKLocationModel];
//    [model poiNearbySearchKeyWord:keyWord finish:^(NSArray *poiInfoArray) {
//        poiSearch(poiInfoArray);
//    }];
//    return model;
//}
//
//+ (BOOL)isOpenLocation
//{
//    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
//    
//    if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {
//        return NO;
//    }else{
//        //定位服务开启
//        return YES;
//    }
//}
@end
